<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" ref="deptTree" />
    <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" :searchInfo="searchInfo">
      <template #toolbar>
        <!-- <a-button type="primary" @click="handleCreate">新增账号</a-button>
        <a-button type="primary" @click="handleExport">导出账号</a-button> -->
        <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
          <a-button class="m-3" :loading="loading"> 导入钉钉部门名册Excel </a-button>
        </ImpExcel>
        <a-button @click="testFn">测试</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:info-standard-line',
                tooltip: '查看用户详情',
                onClick: handleView.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑用户资料',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: '删除此账号',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { aoaToSheetXlsx, ImpExcel } from '@/components/Excel';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { deptUserListApi, importDeptsApi } from '@/api/sys/sysData';
  import { PageWrapper } from '@/components/Page';
  import DeptTree from './DeptTree.vue';

  import { useModal } from '@/components/Modal';
  import AccountModal from './AccountModal.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Modal, Tooltip } from 'ant-design-vue';

  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '@/hooks/web/usePage';

  defineOptions({ name: 'AccountManagement' });

  const loading = ref(false);
  const go = useGo();
  const { createMessage } = useMessage();
  const deptTree = ref();

  const [registerModal, { openModal }] = useModal();
  const searchInfo = reactive<Recordable>({});
  const [registerTable, { reload, updateTableDataRecord, getSearchInfo }] = useTable({
    title: '账号列表',
    api: deptUserListApi,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      console.log('handleSearchInfoFn', info);
      return info;
    },
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    },
  });

  const visible = ref(false);
  const msgList = ref([]);

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    console.log(record);
  }

  function handleExport() {
    console.log(getSearchInfo());
  }

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      // 演示不刷新表格直接更新内部数据。
      // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
      const result = updateTableDataRecord(values.id, values);
      console.log(result);
    } else {
      reload();
    }
  }

  function handleSelect(deptId = '') {
    searchInfo.deptId = deptId;
    reload();
  }

  const arrHeader = [
    {
      key: 'parentName',
      value: '上级部门',
    },
    {
      key: 'parentId',
      value: '上级部门ID',
    },
    {
      key: 'name',
      value: '部门名称',
    },

    {
      key: 'deptId',
      value: '部门ID',
    },
    {
      key: 'count',
      value: '在职人数',
    },
    {
      key: 'manageUserId',
      value: '部门主管userId',
    },
    {
      key: 'manageUserName',
      value: '部门主管',
    },
  ];

  function changeSubmitArr(results) {
    let data = {
      list: [],
    };
    let list = [];
    results.forEach((r) => {
      let json = {};
      for (let key in r) {
        arrHeader.forEach((e) => {
          if (e.value == key) {
            json[e.key] = r[key].trim();
          }
        });
      }
      data.list.push(json);
    });
    return data;
  }

  function excelSuccessFn(list) {
    let results = list[1].results;
    //去除第一行文字提示 shift 删除第一行
    // results.shift();
    // console.log(results);
    let data = changeSubmitArr(results);
    console.log(data);

    loading.value = true;
    importDeptsApi(data)
      .then((res) => {
        loading.value = false;

        if (res.code == 200) {
          if (res.data && res.data.length > 0) {
            // let msg="";
            // for(let i=0;i<res.data.length;i++){
            //   let row= res.data[i];
            //   msg+=`第${row.index}行 ${row.message}\n`
            // }
            msgList.value = res.data;
            visible.value = true;
          } else {
            createMessage.success('导入成功!');
            deptTreeRef.value.fetch();
          }
        } else {
          loading.value = false;

          createMessage.error(res.message);
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  }

  function handleOk() {
    visible.value = false;
  }

  function testFn() {
    deptTree.value.fetch();
  }

  function handleView(record: Recordable) {
    go('/system/account_detail/' + record.id);
  }
</script>
